package main

import (
	"encoding/xml"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"log"
	"main/tools"
	"time"
)

type WXTextMsg struct {
	ToUserName   string
	FromUserName string
	CreateTime   int64
	MsgType      string
	Content      string
	MsgId        int64
}

const port string = ":8080"

var db *gorm.DB

const name string = "root"
const password string = ""

func main() {
	go tools.Postforuser()
	dns := name + ":" + password + "@(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local"
	db, _ = gorm.Open("mysql", dns)

	router := gin.Default()

	router.POST("/wx", WXMsgReceive)

	log.Fatalln(router.Run(port))
}

// WXMsgReceive 微信消息接收
func WXMsgReceive(c *gin.Context) {
	var textMsg WXTextMsg
	err := c.ShouldBindXML(&textMsg)
	if err != nil {
		log.Printf("[消息接收] - XML数据包解析失败: %v\n", err)
		return
	}

	log.Printf("[消息接收] - 收到消息, 消息类型为: %s, 消息内容为: %s\n", textMsg.MsgType, textMsg.Content)
	content := ""
	if textMsg.Content == "学术通知" {
		content = getlink()
	} else {
		content = time.Now().Format("0606-06-06")
	}
	// 对接收的消息进行被动回复
	WXMsgReply(c, textMsg.ToUserName, textMsg.FromUserName, content)
}

// WXRepTextMsg 微信回复文本消息结构体
type WXRepTextMsg struct {
	ToUserName   string
	FromUserName string
	CreateTime   int64
	MsgType      string
	Content      string
	// 若不标记XMLName, 则解析后的xml名为该结构体的名称
	XMLName xml.Name `xml:"xml"`
}

// WXMsgReply 微信消息回复
func WXMsgReply(c *gin.Context, fromUser, toUser, content string) {
	c.Next()
	repTextMsg := WXRepTextMsg{
		ToUserName:   toUser,
		FromUserName: fromUser,
		CreateTime:   time.Now().Unix(),
		MsgType:      "text",
		Content:      content,
	}

	msg, err := xml.Marshal(&repTextMsg)
	if err != nil {
		log.Printf("[消息回复] - 将对象进行XML编码出错: %v\n", err)
		return
	}
	_, _ = c.Writer.Write(msg)
}

type Spyder struct {
	ID     int
	Link   string
	Notice string
}

func getlink() string {
	// 根据struct创建表users
	db.AutoMigrate(&Spyder{})
	var s Spyder
	db.First(&s)
	return s.Notice + ":" + s.Link
}
